package com.ak.movie.repository;

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.ak.es.entity.HighLight;
import com.ak.es.entity.Page;
import com.ak.es.entity.PageSortHighLight;
import com.ak.es.entity.Sort;
import com.ak.es.repository.ElasticsearchTemplate;
import com.ak.movie.entity.Movie;
import com.ak.movie.entity.QueryDTO;

@Repository
public class MovieESRepository implements IMovieRepository {

    @Autowired ElasticsearchTemplate<Movie, String> elasticsearchTemplate;

    @Override
    public boolean save(Movie movie) throws Exception {
    	return elasticsearchTemplate.save(movie);
    }

    @Override
    public Page<Movie> query(String queryString, int pageNo, int size) throws Exception {
        //分页
        PageSortHighLight psh = new PageSortHighLight(pageNo,size);
        //排序
        String sorter = "name.keyword";
        Sort.Order order = new Sort.Order(SortOrder.ASC,sorter);
        psh.setSort(new Sort(order));
        //定制高亮，如果定制了高亮，返回结果会自动替换字段值为高亮内容
        psh.setHighLight(new HighLight().field("description"));
        //可以单独定义高亮的格式
        //new HighLight().setPreTag("<em>");
        //new HighLight().setPostTag("</em>");
        Page<Movie> page = new Page<Movie>(pageNo, size);
        return elasticsearchTemplate.search(page, QueryBuilders.matchQuery("description",queryString), psh, Movie.class);
    }
    
    @Override
    public Page<Movie> query(QueryDTO queryDTO, int pageNo, int size) throws Exception {
    	//分页
        PageSortHighLight psh = new PageSortHighLight(pageNo,size);
        Sort.Order order = new Sort.Order(SortOrder.ASC, queryDTO.getOrderBy());
        psh.setSort(new Sort(order));
        //定制高亮，如果定制了高亮，返回结果会自动替换字段值为高亮内容
        psh.setHighLight(new HighLight().field("description"));
        //可以单独定义高亮的格式
        //new HighLight().setPreTag("<em>");
        //new HighLight().setPostTag("</em>");
        Page<Movie> page = new Page<Movie>(pageNo, size);
        return elasticsearchTemplate.search(page, QueryBuilders.typeQuery("dy2018"), psh, Movie.class);

    }

    @Override
    public Movie get(String id) throws Exception {
        return elasticsearchTemplate.getById(id, Movie.class);
    }

}
